package com.njupt.yanglonglong.report.demo.utils;

import com.njupt.yanglonglong.report.demo.entity.RUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author yangllong
 * @Date 2021/4/28 16:44
 */
@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public RUser getUser(String token) {
        RUser user = (RUser) redisTemplate.opsForValue().get(token);
        if (user != null) {
//            log.info("[用户权限校验成功,token:" + token + ']');
            redisTemplate.expire(token, 1L, TimeUnit.DAYS);
//            log.info("token延时成功:[" + token + "]");
        }
        return user;
    }


    /**
     * 根据 teamId experId 判断报告是否有人在编辑
     *
     * @param key experId_teamId
     * @return user
     */
    public String getIsLocked(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 以 experId_teamId 为 key， userId 为 value 存入 redis
     * 表示该用户正在编辑报告
     * @param key experId_teamId
     * @param userId user
     */
    public void lockReport(String key, String userId) {
        redisTemplate.opsForValue().set(key, userId);
    }

    /**
     * 删除对应 key 值
     * 表示该用户报告编辑已提交
     * @param key experId_teamId
     */
    public void unlockReport(String key) {
        redisTemplate.delete(key);
    }
}
